from __future__ import generators
import os,sys,sets,random
from posnet_overlay_node import posnet_overlay_node,posnet_semantic_query
from posnet_underlays import posnet_underlay_memory

def get_posnet_node(poset):
	overlay_node = posnet_overlay_node(poset,0)
	underlay = posnet_underlay_memory()
	underlay.add(0,overlay_node)
	overlay_node.set_underlay(underlay)
	return overlay_node

def write_dot(node,f):	
	print >>f,"digraph G {"
	node.write_dot(f)
	print >>f,"}"

def save(node,output):
	if False:
		outputf = file(output+".dot","w")	
		write_dot(node,outputf)
		outputf.close()
		os.system("dot -T png -o "+output+".png "+output+".dot")
		#--
	distrib = node.get_degree_distrib()
	f = file(output+".pts","w")
	tot = 0
	distrib.sort()
	last = distrib[0]
	#print >>f,distrib[0],len(distrib)
	print distrib
	number = len(distrib)
	lastnumber = number
	for x in distrib:
		number -= 1
		if last != x:
			print >>f,last,lastnumber
			lastnumber = number
		last = x
	print >>f,last,lastnumber
	f.close()
	import popen2
	out,p = popen2.popen2("gnuplot")
	print >>p,"set term png"
	print >>p,"set output 'deg.png'"
	print >>p,"set log xy"
	print >>p,"plot '"+str(output)+".pts' using 1:2 with linespoints"
	p.close()
	out.close()
	



def test_metrics( dimension, size_of_dimension,nb_objects_by_dimension):
	Poset = dict()
	pushed =  []
	node = None
	try:
		#-----
		keys = []
		num_objects = nb_objects_by_dimension 
		for x in range(dimension):
			keys.append( str(x)+"_"+str(x) )
			if x > 0: num_objects = num_objects * nb_objects_by_dimension
		for k in keys:
			Poset[k] = [2] 	
		#-----
		node = get_posnet_node(Poset)
		num = 0
		while num <  num_objects:
			dat = []
			for j in range(dimension):
				j = int(random.uniform(1,size_of_dimension))
				dat.append(j)
			#print >>sys.stderr,"add",dat
			pushed.append( dat )	
			node.overlay_add_handle(dat,num)
			num += 1
		save(node,"mygraph")
		
		return len(node.overlay_all_top())
	except:
		f = file("error_save.pkl","wb")
		pickle.dump(Poset,f,2)
		pickle.dump(pushed,f,2)
		pickle.dump(node,f,2)
		f.close()
		raise

from poset import read_poset
import pickle
from pprint import pprint


if __name__ == "__main__":

	#dimensions = [3,4]
	dimensions = [5]
	numbers = [100] #,5,10,20,50,100]
	attempts = 1 # 20
	nb_objects_by_dimension = 4
	for dim in dimensions:
		for num in numbers:
			for i in range(attempts):
				core_size = test_metrics(dim,num,nb_objects_by_dimension)
				print dim,num,core_size
				sys.stdout.flush()

